package bestTeam.WalkieDoggie.client.Composites;

import java.util.Date;

import bestTeam.WalkieDoggie.client.WalkieDoggie;
import bestTeam.WalkieDoggie.client.partOfTheDay;
import bestTeam.WalkieDoggie.client.walkieStatus;
import bestTeam.WalkieDoggie.client.Serializables.UserProfileData;
import bestTeam.WalkieDoggie.client.Serializables.UserRequest;

//import com.google.appengine.api.capabilities.CapabilitiesPb.CapabilityConfig.Status;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.HasVerticalAlignment.VerticalAlignmentConstant;
import com.google.gwt.user.datepicker.client.DatePicker;

public class createWalkieComposite extends PopupPanel {

	private Label msg;
	private Label title;
	private DatePicker walkieDate;
	private ListBox walkieTime;
	private Button createWalkieButton;
	private Label creditLabel;

	private int credit;
	private Button cancelBtn;
	private HorizontalPanel hor;

	public createWalkieComposite(){
		super(false);
		msg = new Label();
		createWalkieButton = new Button("Create");
		createWalkieButton.setWidth("100%");
		createWalkieButton.setEnabled(false);

		if(WalkieDoggie.loginInfo.isNewUser()){
			credit = 1;
		}
		else {
			UserProfileData userData = WalkieDoggie.loginInfo.getUserData();
			//TODO: handle this error
			if (userData == null){
				return;
			}
			credit = userData.getCredit();
		}

		title = new Label("A new Walkie");

		walkieDate = new DatePicker();

		//set now to be picked default
		
		walkieDate.setValue(new Date());

		walkieDate.addValueChangeHandler(new ValueChangeHandler<Date>() {

			@Override
			public void onValueChange(ValueChangeEvent<Date> event) {
				if(isValidTime())
					createWalkieButton.setEnabled(true);
//					msg.setText("");				
				else
//					msg.setText("it's in the past..");
					createWalkieButton.setEnabled(false);
			}			
		});

		//walkieDate.setTransientEnabledOnDates(enabled, date)
		walkieTime = new ListBox();

		walkieTime.addItem("Morning (6am-12pm)");
		walkieTime.addItem("Noon (12am-4pm)");
		walkieTime.addItem("Evening (4pm-8pm)");
		walkieTime.addItem("Night (8pm-12am)");

		
		walkieTime.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				if(isValidTime())
					createWalkieButton.setEnabled(true);
//					msg.setText("");				
				else
//					msg.setText("it's in the past..");
					createWalkieButton.setEnabled(false);
			}
		});
		cancelBtn = new Button("Cancel");
		cancelBtn.setWidth("100%");

		

		createWalkieButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				if(isValidTime()){					
					addRequest();
					WalkieDoggie.create_walkies_comp.setGlassEnabled(false);
					WalkieDoggie.create_walkies_comp.hide();
				}
				else
					msg.setText("it's in the past..");
			}
		});

		cancelBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				WalkieDoggie.create_walkies_comp.setGlassEnabled(false);
				WalkieDoggie.create_walkies_comp.hide();
			}
		});

		VerticalPanel verticalPanel = new VerticalPanel();		
		verticalPanel.setSpacing(10);		
		verticalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		verticalPanel.setSize("50px", "100%");
		verticalPanel.add(title);
		verticalPanel.setCellHorizontalAlignment(title, HasHorizontalAlignment.ALIGN_CENTER);
		verticalPanel.add(walkieDate);
		verticalPanel.setCellHorizontalAlignment(walkieDate, HasHorizontalAlignment.ALIGN_CENTER);
		verticalPanel.add(walkieTime);
		verticalPanel.setCellHorizontalAlignment(walkieTime, HasHorizontalAlignment.ALIGN_CENTER);

		creditLabel = new Label("Your credit is: "+credit);
		verticalPanel.add(creditLabel);

		hor = new HorizontalPanel();
		verticalPanel.setCellHorizontalAlignment(hor, HasHorizontalAlignment.ALIGN_CENTER);
		hor.add(cancelBtn);
		hor.add(createWalkieButton);

		hor.setSpacing(10);

		verticalPanel.add(hor);
		verticalPanel.add(msg);
		this.setWidget(verticalPanel);
		//initWidget(verticalPanel);

	}

	@SuppressWarnings("deprecation")
	protected boolean isValidTime() {

		//		walkieDate.getValue();
		//		Calendar cal = Calendar.getInstance();
		//		DateTime d = new DateTime();


		Date now = new Date();
		Date wantedDated = walkieDate.getValue();
		int hour=0;

		switch (walkieTime.getSelectedIndex()) {
		case 0:  hour = 6;
		break;
		case 1:  hour = 12;
		break;
		case 2:  hour = 16;
		break;
		case 3:  hour = 20;
		break;
		}  

		wantedDated.setHours(hour);

		return !wantedDated.before(now);
	}

	public Date getWalkieDate(){

		return walkieDate.getValue();
	}

	public partOfTheDay getWalkiePartOfTheDay(){

		int a = walkieTime.getSelectedIndex();
		if (a==0)
			return partOfTheDay.Morning;
		if (a==1)
			return partOfTheDay.Noon;
		if (a==2)
			return partOfTheDay.Evening;
		else
			return partOfTheDay.Night;
	}

	public Button getCreateButton(){
		return this.createWalkieButton;
	}

	private void addRequest(){

		//final Date selectedDate = datePicker.getValue();
		final Date selectedDate = this.getWalkieDate();

		if(selectedDate==null){	
			WalkieDoggie.handleError(new Throwable("man!! you've gotta select a date!"));
			return;
		}

		final UserRequest newRequest = new UserRequest();
		newRequest.setUserName(WalkieDoggie.loginInfo.getUserData().getNickName());
		newRequest.setCreationDate(new Date());
		newRequest.setDate(selectedDate);
		newRequest.setStatus(walkieStatus.NEW);
		newRequest.setTimeFrame(getWalkiePartOfTheDay().toString());
		UserProfileData userData = WalkieDoggie.loginInfo.getUserData();
		//TODO: handle this error
		if (userData == null){
			return;
		}
		String myDogName = userData.getDogName();
		String myNickName = WalkieDoggie.loginInfo.getUserData().getNickName();


		newRequest.setMessage(myNickName+":\tPlease take "+myDogName+" out at "+newRequest.getTimeFrame() );
		newRequest.setCreatedBy(WalkieDoggie.loginInfo.getUserData().getId());
		WalkieDoggie.requestService.addRequest(newRequest, new AsyncCallback<String>() {
			public void onFailure(Throwable error) {
				WalkieDoggie.handleError(error);
			}
			public void onSuccess(String id) {


				newRequest.setId(id);
				WalkieDoggie.my_walkies_comp.addRequestDisplay(newRequest);

				WalkieDoggie.mainPanel.clear();
				WalkieDoggie.mainPanel.add(WalkieDoggie.my_walkies_comp);

				decreaseCredit();


			}


		});

	}

	private void decreaseCredit() {
		WalkieDoggie.usersService.setCredits(WalkieDoggie.loginInfo.getUserData().getId(), -1,new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				WalkieDoggie.handleError(caught);

			}

			@Override
			public void onSuccess(Void result) {
				setCredit(credit-1);
				WalkieDoggie.side_comp.getCredit_label().setText("your credit: "+credit);
				WalkieDoggie.updateCounters();

			}
		});

	}

	public void increaseCredit() {
		WalkieDoggie.usersService.setCredits(WalkieDoggie.loginInfo.getUserData().getId(), +1,new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				WalkieDoggie.handleError(caught);

			}

			@Override
			public void onSuccess(Void result) {
				setCredit(credit+1);
				WalkieDoggie.side_comp.getCredit_label().setText("your credit: "+credit);
				WalkieDoggie.updateCounters();

			}
		});

	}

	void setCredit(int credit){
		this.credit = credit;
		creditLabel.setText("Your credit is: "+credit);
	}


	int getCredit() {
		return credit;
	}

}
